/**
 * @Title: RecordAddOrUpdateActivity.java
 * @Package: com.jason.fingerprint.ui
 * @Descripton: TODO
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年11月2日 上午2:47:52
 * @Version: V1.0
 */
package com.jason.fingerprint.ui;

import org.kymjs.aframe.ui.BindView;
import org.kymjs.aframe.ui.KJActivityManager;
import org.kymjs.aframe.ui.activity.BaseActivity;
import org.kymjs.aframe.utils.StringUtils;
import org.kymjs.aframe.utils.SystemTool;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.R;
import com.jason.fingerprint.beans.RecordBean;
import com.jason.fingerprint.common.DialogHelper;
import com.jason.fingerprint.common.UIHelper;
import com.jason.fingerprint.logic.InsertOrUpdateSyncLogic;
import com.jason.fingerprint.logic.RegisterFingerprintSyncLogic;
import com.jason.fingerprint.utils.CodecUtils;
import com.jason.fingerprint.widget.LoadingDialog;
import com.jason.fingerprint.widget.PopWindow;

/**
 * @ClassName: RecordAddOrUpdateActivity
 * @Description: 指纹录入或修改
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年11月2日 上午2:47:52
 */
@SuppressLint("HandlerLeak")
public class RecordAddOrUpdateActivity extends BaseActivity {

	private static final String TAG = "RecordAddOrUpdateActivity";

	public static final String RECORD_STATE = "record_state";
	public static final String RECORD_INFO = "RECORD_INFO";
	public static final String RECORD_ADD_FIELD_CONTENT = "record_add_field_content";
	public static final int UPDATE_RECORD_STATE = 2000;
	public static final int ADD_RECORD_STATE = 2001;

	public static final String ADD_NAME = "add_name";
	public static final String ADD_TELEPHONE = "add_telephone";
	public static final String ADD_IDENTITYNO = "add_identityNO";
	public static final String ADD_REGISTERED = "add_registered";
	public static final String ADD_REGISTEREDID = "add_registeredid";
	public static final String ADD_FP1 = "add_fp1";
	public static final String ADD_FP2 = "add_fp2";
	public static final String ADD_CARDNO = "add_cardNo";

	public static final int REQUEST_NAME_CODE = 10000;
	public static final int REQUEST_TELEPHONE_CODE = 10001;
	public static final int REQUEST_IDENTITYNO_CODE = 10002;
	public static final int REQUEST_REGISTERED_CODE = 10003;
	public static final int REQUEST_CARDNO_CODE = 10004;

	@BindView(id = R.id.tv_name)
	private TextView mNameTextView;// 姓名
	@BindView(id = R.id.record_add_name_layout, click = true)
	private RelativeLayout mNameLayout;// 姓名

	@BindView(id = R.id.tv_telephone)
	private TextView mTelephoneTextView;// 手机号码
	@BindView(id = R.id.record_add_telephone_layout, click = true)
	private RelativeLayout mTelephoneLayout;

	@BindView(id = R.id.tv_identityNO)
	private TextView mIdentityNOTextView;// 身份证号
	@BindView(id = R.id.record_add_identityNO_layout, click = true)
	private RelativeLayout mIdentityNOLayout;

	@BindView(id = R.id.tv_registered)
	private TextView mRegisteredTextView;// 隶属机构名称
	@BindView(id = R.id.record_add_registered_layout, click = true)
	private RelativeLayout mRegisteredLayout;

	@BindView(id = R.id.tv_fp1)
	private TextView mFp1TextView;
	@BindView(id = R.id.record_add_fp1_layout, click = true)
	private RelativeLayout mFp1Layout;

	@BindView(id = R.id.tv_fp2)
	private TextView mFp2TextView;
	@BindView(id = R.id.record_add_fp2_layout, click = true)
	private RelativeLayout mFp2Layout;

	@BindView(id = R.id.tv_cardNo)
	private TextView mCardNoTextView;// RFID卡号
	@BindView(id = R.id.record_add_cardNo_layout, click = true)
	private RelativeLayout mCardNoLayout;

	@BindView(id = R.id.header_back, click = true)
	private Button mBackButton;
	@BindView(id = R.id.header_title)
	private TextView mTitleTextView;
	@BindView(id = R.id.header_complete, click = true)
	private Button mCompleteButton;
	@BindView(id = R.id.record_add_main_layout)
	private View mMainLayout;

	private String mRecordName;
	private String mRecordTelephone;
	private String mRecordIdentityNO;
	private String mRecordRegistered;
	private String mRecordRegisteredId;
	private String mRecordFp1;
	private String mRecordFp2;
	private String mRecordCardNo;
	private String mRecordElectronicsId;

	private int mRecordState;
	private RecordBean mRecordBean;
	private RecordBean mRequestRecordBean;
	private AppContext mAppContext;
	private LoadingDialog mProgressDialog;
	private byte[] mModel;
	private String mFingerInfo;
	private int mFingerState = 1;
	
	@Override
	public void setRootView() {
		setContentView(R.layout.activity_record_add);
	}

	@Override
	protected void initWidget() {
		super.initWidget();
		mAppContext = (AppContext) getApplication();
		mCompleteButton.setVisibility(View.VISIBLE);
	}

	@Override
	protected void initData() {
		super.initData();
		mProgressDialog = new LoadingDialog(this);
		initDatas();

	}

	@Override
	protected void onResume() {
		super.onResume();
		//initDatas();
	}

	private void showPopWindow() {
		mProgressDialog.setMessage("请按手指...");
		mProgressDialog.show();
		RegisterFingerprintSyncLogic logic = new RegisterFingerprintSyncLogic(
				mAppContext, mFingerpringHandler, true, false);
		logic.execute();
	}

	private void initDatas() {
		mRequestRecordBean = new RecordBean();
		Intent intent = getIntent();
		mTitleTextView.setText("指纹录入");
		if (intent != null) {
			mRecordState = intent.getIntExtra(RECORD_STATE, ADD_RECORD_STATE);
			mRecordBean = (RecordBean) intent
					.getSerializableExtra("RecordBean");
			Log.i(TAG, "initDatas " + mRecordBean);
			if (mRecordBean != null) {
				mTitleTextView.setText(mRecordBean.getName());
				mNameTextView.setText(mRecordBean.getName());
				mTelephoneTextView.setText(mRecordBean.getTelephone());
				mIdentityNOTextView.setText(mRecordBean.getIdentityNO());
				mRegisteredTextView.setText(mRecordBean.getRegistered());
				mCardNoTextView.setText(mRecordBean.getCardNO());
				if (StringUtils.isEmpty(mRecordBean.getFp_1())) {
					mFp1TextView.setText("未录");
				} else {
					mFp1TextView.setText("已录");
				}
				if (StringUtils.isEmpty(mRecordBean.getFp_2())) {
					mFp2TextView.setText("未录");
				} else {
					mFp2TextView.setText("已录");
				}
				mRecordRegisteredId = mRecordBean.getRegisteredId();
				mRecordElectronicsId = mRecordBean.getElectronicsId();
			}
		}
	}

	@Override
	public void widgetClick(View v) {
		Intent intent = new Intent(RecordAddOrUpdateActivity.this,
				RecordAddFieldActivity.class);
		super.widgetClick(v);
		switch (v.getId()) {
		case R.id.header_back:
			KJActivityManager.create().finishActivity(
					RecordAddOrUpdateActivity.this);
			break;
		case R.id.record_add_name_layout:
			intent.putExtra(RECORD_STATE, "姓名");
			intent.putExtra(RECORD_INFO, mNameTextView.getText().toString());
			startActivityForResult(intent, REQUEST_NAME_CODE);
			break;
		case R.id.record_add_telephone_layout:
			intent.putExtra(RECORD_STATE, "手机号码");
			intent.putExtra(RECORD_INFO, mTelephoneTextView.getText()
					.toString());
			startActivityForResult(intent, REQUEST_TELEPHONE_CODE);
			break;
		case R.id.record_add_identityNO_layout:
			intent.putExtra(RECORD_STATE, "身份证号");
			intent.putExtra(RECORD_INFO, mIdentityNOTextView.getText()
					.toString());
			startActivityForResult(intent, REQUEST_IDENTITYNO_CODE);
			break;
		case R.id.record_add_registered_layout:
			Intent in = new Intent(RecordAddOrUpdateActivity.this,
					ChooseOrganActivty.class);
			in.putExtra(RECORD_STATE, "选择机构");
			startActivityForResult(in, REQUEST_REGISTERED_CODE);
			break;
		case R.id.record_add_fp1_layout:
			mFingerState = 1;
			showPopWindow();
			break;
		case R.id.record_add_fp2_layout:
			mFingerState = 2;
			showPopWindow();
			break;
		case R.id.record_add_cardNo_layout:
			intent.putExtra(RECORD_STATE, "监管卡号");
			intent.putExtra(RECORD_INFO, mCardNoTextView.getText().toString());
			startActivityForResult(intent, REQUEST_CARDNO_CODE);
			break;
		case R.id.header_complete:
			// 完成，调用录入接口
			if (!SystemTool.checkNet(AppContext.getAppContext())) {
				DialogHelper
						.openNetSettingsDialog(RecordAddOrUpdateActivity.this);
			} else {
				mProgressDialog.show();
				updateRecordData();
				if (mRecordState == ADD_RECORD_STATE) {
					// 新添加数据
					mRequestRecordBean.setType("0");
				} else {
					// 修改数据
					mRequestRecordBean.setType("1");
					mRequestRecordBean.setId(mRecordBean.getId());
				}
				// TODO 调用服务器接口
				InsertOrUpdateSyncLogic logic = new InsertOrUpdateSyncLogic(
						mAppContext, mAddHandler, true, mRequestRecordBean);
				logic.execute();
			}
			break;
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != RESULT_OK) {
			return;
		}
		String content = null;
		String machId = null;
		if (data != null) {
			content = data.getStringExtra(RECORD_ADD_FIELD_CONTENT);
		}
		Log.i(TAG, "----> onActivityResult content:" + content + ",machId:"
				+ machId + ",requestCode:" + requestCode + ",resultCode:" + resultCode);
		switch (requestCode) {
		case REQUEST_NAME_CODE:
			mTitleTextView.setText(content);
			mNameTextView.setText(content);
			mRecordName = content;
			//updateName(content);
			break;
		case REQUEST_TELEPHONE_CODE:
			mTelephoneTextView.setText(content);
			mRecordTelephone = content;
			break;
		case REQUEST_IDENTITYNO_CODE:
			mIdentityNOTextView.setText(content);
			mRecordIdentityNO = content;
			break;
		case REQUEST_REGISTERED_CODE:
			machId = data.getStringExtra("machId");
			mRegisteredTextView.setText(content);
			mRecordRegistered = content;
			mRecordRegisteredId = machId;
			Log.i(TAG, "----> onActivityResult content:" + content + ",machId:"
					+ machId);
			break;
		case REQUEST_CARDNO_CODE:
			mCardNoTextView.setText(content);
			mRecordCardNo = content;
			break;

		default:
			break;
		}
	}

	private void updateRecordData() {
		mRecordName = mNameTextView.getText().toString();
		mRecordTelephone = mTelephoneTextView.getText().toString();
		mRecordCardNo = mCardNoTextView.getText().toString();
		mRecordIdentityNO = mIdentityNOTextView.getText().toString();
		mRecordRegistered = mRegisteredTextView.getText().toString();
		if (StringUtils.isEmpty(mRecordName)) {
			Toast.makeText(this, "姓名不能为空", Toast.LENGTH_SHORT).show();
			return;
		}
		if (StringUtils.isEmpty(mRecordIdentityNO)) {
			Toast.makeText(this, "身份证号码不能为空", Toast.LENGTH_SHORT).show();
			return;
		}
		if (StringUtils.isEmpty(mRecordRegistered)
				|| StringUtils.isEmpty(mRecordRegisteredId)) {
			Toast.makeText(this, "机构名称不能为空", Toast.LENGTH_SHORT).show();
			return;
		}
		mRequestRecordBean.setName(mRecordName);
		mRequestRecordBean.setTelephone(mRecordTelephone);
		mRequestRecordBean.setCardNO(mRecordCardNo);
		mRequestRecordBean.setIdentityNO(mRecordIdentityNO);
		mRequestRecordBean.setRegistered(mRecordRegistered);
		mRequestRecordBean.setRegisteredId(mRecordRegisteredId);
		mRequestRecordBean.setFp_1(mRecordFp1);
		mRequestRecordBean.setFp_2(mRecordFp2);
		mRequestRecordBean.setElectronicsId(mRecordElectronicsId);
	}

	private Handler mAddHandler = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			if (mProgressDialog != null) {
				mProgressDialog.dismiss();
			}
			String tip = (String) msg.obj;
			switch (msg.what) {
			case 0:
				if (mRecordState == ADD_RECORD_STATE) {
					// TODO 保存当期的指纹信息到设备，后期优化,同时修改指纹录入界面的信息
					
				}
				break;
			case 1:
				break;

			default:
				break;
			}
			sendBroadcast(new Intent(RecordActivity.UPDATE_RECORD_ACTION));
			Toast.makeText(getApplicationContext(), tip, Toast.LENGTH_SHORT)
					.show();

		};
	};

	private Handler mFingerpringHandler = new Handler() {

		String toast = "失败";

		@Override
		public void handleMessage(Message msg) {
			Bundle bundle = msg.getData();
			switch (msg.what) {
			case UIHelper.FINGERPRINT_UPCHAR_SUCCESS:
				// char--返回成功
				if (bundle != null) {
					mModel = bundle.getByteArray(UIHelper.FINGERPRINT_SOURCE);
				}
				Toast.makeText(RecordAddOrUpdateActivity.this, "指纹录入成功", Toast.LENGTH_SHORT).show();
				mFingerInfo = CodecUtils.base64EncodeToString(mModel);
				if (mFingerState == 1) {
					mFp1TextView.setText("已录");
					mRecordFp1 = mFingerInfo;
				} else if (mFingerState == 2) {
					mFp2TextView.setText("已录");
					mRecordFp2 = mFingerInfo;
				}
				if (mProgressDialog != null && mProgressDialog.isShowing()) {
					mProgressDialog.dismiss();
				}
				break;
			case UIHelper.FINGERPRINT_UPCHAR_FAIL:// char--返回失败
			case UIHelper.FINGERPRINT_REGMODE_FAIL:// char--模板合成失败
			case UIHelper.FINGERPRINT_GENCHAR_FAIL:// char--生成特征值失败
			case UIHelper.FINGERPRINT_DELETECHAR_FAIL:// char--模板下载失败
			case UIHelper.FINGERPRINT_ONMATCH_FAIL:// char--匹配失败
			case UIHelper.FINGERPRINT_UPIMAGE_FAIL:// image--生成失败
				Toast.makeText(RecordAddOrUpdateActivity.this, "指纹录入失败", Toast.LENGTH_SHORT).show();
				break;
			case UIHelper.FINGERPRINT_AGAIN:// 再次按手指
				mProgressDialog.setMessage("请再次按下手指...");
				mProgressDialog.show();
				break;

			case UIHelper.FINGERPRINT_UPIMAGE_SUCCESS:// image--图片合成成功
				break;
			case UIHelper.FINGERPRINT_ONMATCH_SUCCESS:// image--图片合成成功
				Toast.makeText(RecordAddOrUpdateActivity.this, "指纹录入成功", Toast.LENGTH_SHORT).show();
				break;

			default:
				break;
			}
		};

	};
}
